package com.akami.recipe;

import java.io.UnsupportedEncodingException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import xframe.ctl.XDispatchAction;
import xframe.util.UtilMaster;
import xframe.util.db.Row;
import xframe.util.db.Transaction;

public class RecipeStepAction extends XDispatchAction {
	public ActionForward move( 	ActionMapping       mapping,
			ActionForm          form,
			HttpServletRequest  request,
			HttpServletResponse response ) throws Exception { 

		Row	req			=	getRequestInfo(request);
		
		
		
		
		return mapping.findForward((String) req.get("NEXT_PAGE") );
	}
	
	public ActionForward recipeStepOne( 	ActionMapping       mapping,
			ActionForm          form,
			HttpServletRequest  request,
			HttpServletResponse response ) throws Exception {

		Row	req			=	getRequestInfo(request);
		try{		
		// 디비연결 시작
		Transaction.start(request);		
		

		String queryName	=	"recipe.insert";		
		String recipe_pk		=	System.nanoTime()+"";
		req.put("recipe_pk",recipe_pk);
		req.put("publish_code","S1P0P0");
		
		req.put("writer_email","akami.java@gmail.com");
		req.put("write_name","강백석");
		
		String	query 	=	mappingQuery(req, queryName);
		String[] preparedIndex = {
				"recipe_pk",
				"season_code",
				"old_code",
				"taste_code",
				"situation_code",
				"nationStyle_code",
				"main_material_code",
				"title",
				"summary",
				"forMan",
				"unit",
				"cookTime",
				"discription",
				"tip",
				"publish_code",
				"writer_email",
				"write_name"
				};
		//PreparedStatement  실행
		preparedExecuteUpdate(request, req, preparedIndex, query);	
		
		
		//queryName	=	"newsMaster.insertKeyword";	
		
		
		
		String[] keyword = (String[])req.get("ref_keyword");
		
		
		//for(int i =0 ; i < keyword.length ; i++){
			//req.put("ref_keyword",keyword[i]);
			//query 	=	mappingQuery(req, queryName);
			//simpleExecuteUpdate(request, query, queryName);
		//}
		
		request.setAttribute("nextPage", request.getContextPath()+"/recipe.do?command=getRecipeTwo&recipe_pk="+recipe_pk);

		//디비연결 종
        Transaction.end(request);
												
		}catch(Exception e){
			e.printStackTrace();
			Transaction.rollback(request, response);
			req.put("system_error", e.getMessage());
			return mapping.findForward( "system_error" );			
		} 
		
        return mapping.findForward( "sendRedirect" ); 
	}
	
	
	public ActionForward writeRecipeStep2( 	ActionMapping       mapping,
			ActionForm          form,
			HttpServletRequest  request,
			HttpServletResponse response ) throws Exception {
		
		Row	req			=	getRequestInfo(request);
		try{		
			// 디비연결 시작
			Transaction.start(request);		
			
			String 	listQueryName	=	"recipe.getrecipeStepone";
			String	listQuery 		=	mappingQuery(req, listQueryName);	
			Row resultRow = simpleExecuteQueryGetOneRow(request, listQuery, listQueryName);	
			request.setAttribute("resultRow",resultRow);
			
		}catch(Exception e){
			e.printStackTrace();
			Transaction.rollback(request, response);
			req.put("system_error", e.getMessage());
			return mapping.findForward( "system_error" );			
		} 
		
		return mapping.findForward( "writeRecipeStep2" ); 
	}
	
	public ActionForward list( 	ActionMapping       mapping,
			ActionForm          form,
			HttpServletRequest  request,
			HttpServletResponse response ) throws Exception {
		
		Row	req			=	getRequestInfo(request);
		try{		
			// 디비연결 시작
			Transaction.start(request);		
			
	        // 전체 게시물 갯수
			String totalQueryName	=	"recipe.getrecipeListCount";		
			String	totalQuery 	=	mappingQuery(request, totalQueryName);
			
			simpleExecuteQueryGetOneRow(request, totalQuery, totalQueryName);
			
			Row	SUM_LIST	=	(Row)request.getAttribute(totalQueryName);			
			req.put("TOTAL", SUM_LIST.getString("TOTAL"));					
			int start_row 	=	0;
			int page		=	0;
			//페이지 파라미터 점검
			//첫페이지는 파라미터가 없으므로 0이나 1로 셋팅한다.
			if(req.get("page") ==null || ((String)req.get("page")).trim().length() == 0 ){
				page	=	1;
			}else  {
				try{
					page	=	Integer.parseInt(((String)req.get("page")));
				}catch(Exception e){
					page	=	1;
				}
			}
			start_row	=	(page	-	1)	*	10;
			req.put("start_row", start_row+"");
			req.put("page", page+"");
			
			//전체게시물의 갯수를 토대로 다시 쿼리를 날려서 원하는 데이터만 받아온다.		
			String 	listQueryName	=	"recipe.getrecipeList";
			String	listQuery 		=	mappingQuery(req, listQueryName);	
	
			simpleExecuteQuery(request, listQuery, listQueryName);	
			
			//디비연결 종
			Transaction.end(request);
			
		}catch(Exception e){
			e.printStackTrace();
			Transaction.rollback(request, response);
			req.put("system_error", e.getMessage());
			return mapping.findForward( "system_error" );			
		} 
		
		return mapping.findForward( "list" ); 
	}
	
	
	
	
	public ActionForward getRecipeOne( 	ActionMapping       mapping,
			ActionForm          form,
			HttpServletRequest  request,
			HttpServletResponse response ) throws Exception {
			Row	req			=	getRequestInfo(request);
		try{
			// 디비연결 시작
			Transaction.start(request);		
			
			String 	listQueryName	=	"recipe.getRecipeOne";
			String	listQuery 		=	mappingQuery(req, listQueryName);	
			Row resultRow = simpleExecuteQueryGetOneRow(request, listQuery, listQueryName);												
	        request.setAttribute("resultRow", resultRow);
			
			listQueryName	=	"recipe.getKeyword";
			listQuery 		=	mappingQuery(req, listQueryName);	
			simpleExecuteQuery(request, listQuery, listQueryName);												
			
			
			request.setAttribute("resultRow",resultRow);
			//디비연결 종
	        Transaction.end(request);
        
		}catch(Exception e){
			e.printStackTrace();
			Transaction.rollback(request, response);
			req.put("system_error", e.getMessage());
			return mapping.findForward( "system_error" );			
		}    		
	return mapping.findForward("getRecipeStep1");
	}
	
	public ActionForward getRecipeTwo( 	ActionMapping       mapping,
			ActionForm          form,
			HttpServletRequest  request,
			HttpServletResponse response ) throws Exception {
		Row	req			=	getRequestInfo(request);
		try{
			// 디비연결 시작
			Transaction.start(request);		
			
			String 	listQueryName	=	"recipe.getRecipeOne";
			String	listQuery 		=	mappingQuery(req, listQueryName);	
			Row resultRow = simpleExecuteQueryGetOneRow(request, listQuery, listQueryName);												
			request.setAttribute("resultRowTab1", resultRow);
			
			listQueryName	=	"recipe.getKeyword";
			listQuery 		=	mappingQuery(req, listQueryName);	
			simpleExecuteQuery(request, listQuery, listQueryName);												
			
			
			request.setAttribute("resultRow",resultRow);
			
			listQueryName	=	"recipe.selectMaterial";
			listQuery 		=	mappingQuery(req, listQueryName);	
			simpleExecuteQuery(request, listQuery, listQueryName);
			
			listQueryName	=	"recipe.attachementUploadSelect";
			listQuery 		=	mappingQuery(req, listQueryName);	
    		simpleExecuteQuery(request, listQuery, listQueryName);
    		
    		listQueryName	=	"recipe.attachementStepByStep";
    		listQuery 		=	mappingQuery(req, listQueryName);	
    		simpleExecuteQuery(request, listQuery, listQueryName);
    		
			//디비연결 종
			Transaction.end(request);
			
		}catch(Exception e){
			e.printStackTrace();
			Transaction.rollback(request, response);
			req.put("system_error", e.getMessage());
			return mapping.findForward( "system_error" );			
		}    		
		return mapping.findForward("getRecipeStep2");
	}
	
	
	public ActionForward recipeStepOneUpdate( 	ActionMapping       mapping,
			ActionForm          form,
			HttpServletRequest  request,
			HttpServletResponse response ) throws Exception {
		Row	req			=	getRequestInfo(request);
		try{
			// 디비연결 시작
			Transaction.start(request);		
			String 	queryName	=	"recipe.recipeStepOneUpdate";
			String	query 	=	mappingQuery(req, queryName);
			String[] preparedIndex = {
					"season_code",
					"old_code",
					"taste_code",
					"situation_code",
					"main_material_code",
					"nationStyle_code",
					"title",
					"summary",
					"forMan",
					"unit",
					"cookTime",
					"discription",
					"tip",
					"publish_code",
					"writer_email",
					"write_name",
					"recipe_pk"
					};
			//PreparedStatement  실행
			preparedExecuteUpdate(request, req, preparedIndex, query);	
			
			

			
			queryName	=	"recipe.deleteKeyword";
			query 	=	mappingQuery(req, queryName);
			simpleExecuteUpdate(request, query, queryName);
			
			queryName	=	"recipe.insertKeyword";	
			
			String[] keyword = (String[])req.get("tag");
			for(int i =0 ; i < keyword.length ; i++){
				if(keyword[i].trim().length() > 0 )
				req.put("keyword",keyword[i]);
				query 	=	mappingQuery(req, queryName);
				System.out.println("===========================");
				System.out.println(query);
				System.out.println("===========================");
				String[] preparedIndex2 = {
						"keyword",
						"recipe_pk",
						"reg_name",
						"reg_email"
						};
				//PreparedStatement  실행
				preparedExecuteUpdate(request, req, preparedIndex2, query);	
			}											
			
			
			//디비연결 종
			Transaction.end(request);
			request.setAttribute("nextPage", request.getContextPath()+"/recipe.do?command=getRecipeTwo&recipe_pk="+req.get("recipe_pk"));

													
			}catch(Exception e){
				e.printStackTrace();
				Transaction.rollback(request, response);
				req.put("system_error", e.getMessage());
				return mapping.findForward( "system_error" );			
			} 
			
			return mapping.findForward("sendRedirect");
	}
	
	public ActionForward addMaterial( 	ActionMapping       mapping,
			ActionForm          form,
			HttpServletRequest  request,
			HttpServletResponse response ) throws Exception {
		
		Row	req			=	getRequestInfo(request);
		try{		
		// 디비연결 시작
		Transaction.start(request);		
		
		HttpSession session = request.getSession();
		req.put("reg_email", session.getAttribute("s_email"));
		req.put("upd_email", session.getAttribute("s_email"));
		req.put("upd_tel", session.getAttribute("s_tel"));
		

		String queryName	=	"recipe.addMaterial";		
		String	query 	=	mappingQuery(req, queryName);
		String[] preparedIndex = {
				"recipe_pk",            
				"material_code",            
				"material_nm",            
				"unit_code",            
				"unit_nm",            
				"cnt"           
				};
		//PreparedStatement  실행
		preparedExecuteUpdate(request, req, preparedIndex, query);	

		//디비연결 종
        Transaction.end(request);
        
		req.put("SUCCESS_FAIL", "SUCCESS");
		req.put("MESSAGE", "추가되었습니다.");
		
		return mapping.findForward( "success_fail" );         
												
		}catch(Exception e){
			e.printStackTrace();
			Transaction.rollback(request, response);
			req.put("system_error", e.getMessage());
			req.put("SUCCESS_FAIL", "FAIL");
			req.put("MESSAGE", "이미 입력된 재료이거나 잘못된 재료입니다.");
			return mapping.findForward( "success_fail" );			
		} 
		
	}
	
	
	public ActionForward deleteMaterial( 	ActionMapping       mapping,
			ActionForm          form,
			HttpServletRequest  request,
			HttpServletResponse response ) throws Exception {
		
		Row	req			=	getRequestInfo(request);
		try{		
		// 디비연결 시작
		Transaction.start(request);		
		
		HttpSession session = request.getSession();
		req.put("reg_email", session.getAttribute("s_email"));
		req.put("upd_email", session.getAttribute("s_email"));
		req.put("upd_tel", session.getAttribute("s_tel"));
		

		String queryName	=	"recipe.deleteMaterial";		
		String	query 	=	mappingQuery(req, queryName);
		String[] preparedIndex = {
				"recipe_pk",            
				"material_code" 
				};
		//PreparedStatement  실행
		preparedExecuteUpdate(request, req, preparedIndex, query);	

		//디비연결 종
        Transaction.end(request);
        
		req.put("SUCCESS_FAIL", "SUCCESS");
		req.put("MESSAGE", "삭제되었습니다.");
		
		return mapping.findForward( "success_fail" );         
												
		}catch(Exception e){
			e.printStackTrace();
			Transaction.rollback(request, response);
			req.put("system_error", e.getMessage());
			req.put("SUCCESS_FAIL", "FAIL");
			req.put("MESSAGE", "삭제 실패");
			return mapping.findForward( "success_fail" );			
		} 
		
	}
	
	
	
	public ActionForward setPublic( 	ActionMapping       mapping,
			ActionForm          form,
			HttpServletRequest  request,
			HttpServletResponse response ) throws Exception {
		
		Row	req			=	getRequestInfo(request);
		try{		
			// 디비연결 시작
			Transaction.start(request);		
			
			HttpSession session = request.getSession();
			req.put("reg_email", session.getAttribute("s_email"));
			req.put("upd_email", session.getAttribute("s_email"));
			
			String queryName	=	"recipe.setPublic";		
			
			String	query 	=	mappingQuery(req, queryName);
			
			String[] preparedIndex = {
					"publish_code",   
					"recipe_pk"   
			};
			//PreparedStatement  실행
			preparedExecuteUpdate(request, req, preparedIndex, query);	
			
			
			request.setAttribute("nextPage", request.getContextPath()+"/news.do?command=select");
			
			//디비연결 종
			Transaction.end(request);
			req.put("SUCCESS_FAIL", "SUCCESS");
			req.put("MESSAGE", "추가되었습니다.");
			
			   
													
			}catch(Exception e){
				e.printStackTrace();
				Transaction.rollback(request, response);
				req.put("system_error", e.getMessage());
				req.put("SUCCESS_FAIL", "FAIL");
				req.put("MESSAGE", "이미 입력된 재료이거나 잘못된 재료입니다.");
				return mapping.findForward( "success_fail" );			
			} 
		
			return mapping.findForward( "success_fail" );      
	}	
	
	
	
	
	
	
	
	public ActionForward newsPreview( 	ActionMapping       mapping,
			ActionForm          form,
			HttpServletRequest  request,
			HttpServletResponse response ) throws Exception {
		Row	req			=	getRequestInfo(request);
		try{
			// 디비연결 시작
			Transaction.start(request);		
			
			String 	listQueryName	=	"newsMaster.newsPreview";
			String	listQuery 		=	mappingQuery(req, listQueryName);	
			Row resultRow = simpleExecuteQueryGetOneRow(request, listQuery, listQueryName);												
			
			
			listQueryName	=	"newsMaster.newsPreviewKeyword";
			listQuery 		=	mappingQuery(req, listQueryName);	
			simpleExecuteQuery(request, listQuery, listQueryName);												
			
			
			request.setAttribute("resultRow",resultRow);
			//디비연결 종
			Transaction.end(request);
			
		}catch(Exception e){
			e.printStackTrace();
			Transaction.rollback(request, response);
			req.put("system_error", e.getMessage());
			return mapping.findForward( "system_error" );			
		}    		
		return mapping.findForward("newsPreview");
	}
	
	
	public ActionForward newsInsert( 	ActionMapping       mapping,
			ActionForm          form,
			HttpServletRequest  request,
			HttpServletResponse response ) throws Exception {
		
		Row	req			=	getRequestInfo(request);
		try{		
		// 디비연결 시작
		Transaction.start(request);		
		
		HttpSession session = request.getSession();
		req.put("reg_email", session.getAttribute("s_email"));
		req.put("upd_email", session.getAttribute("s_email"));
		req.put("upd_tel", session.getAttribute("s_tel"));
		

		String queryName	=	"newsMaster.insert";		
		String news_idx		=	System.nanoTime()+"";
		req.put("news_idx",news_idx);
		req.put("sisa",req.getString("sisa").replaceAll("\n", "<br>"));
		
		//req.get(UtilMaster.convertHtml(req.getString("title")));
		//req.get(UtilMaster.convertHtml(req.getString("headline")));
		
		String	query 	=	mappingQuery(req, queryName);
		String[] preparedIndex = {
				"news_idx",            
				"part_code",            
				"ref_url",            
				"ref_date",            
				"title",            
				"sisa",            
				"headline",            
				"content_html",            
				"ref_code",            
				"reg_name",            
				"reg_email",            
				"reg_name",            
				"upd_email",            
				"upd_tel"            
				};
		//PreparedStatement  실행
		preparedExecuteUpdate(request, req, preparedIndex, query);	
		
		
		queryName	=	"newsMaster.insertKeyword";	
		
		
		
		String[] keyword = (String[])req.get("ref_keyword");
		
		
		for(int i =0 ; i < keyword.length ; i++){
			req.put("ref_keyword",keyword[i]);
			query 	=	mappingQuery(req, queryName);
			simpleExecuteUpdate(request, query, queryName);
		}
		
		request.setAttribute("nextPage", request.getContextPath()+"/news.do?command=select");

		//디비연결 종
        Transaction.end(request);
												
		}catch(Exception e){
			e.printStackTrace();
			Transaction.rollback(request, response);
			req.put("system_error", e.getMessage());
			return mapping.findForward( "system_error" );			
		} 
		
		return mapping.findForward("sendRedirect");
	}
	
	
	
	public ActionForward mainMaterailSet( 	ActionMapping       mapping,
			ActionForm          form,
			HttpServletRequest  request,
			HttpServletResponse response ) throws Exception {
		
		Row	req			=	getRequestInfo(request);
		

		try{
			// 디비연결 시작
			Transaction.start(request);		
			
			HttpSession session = request.getSession();
			req.put("s_name", session.getAttribute("name"));
			req.put("s_email", session.getAttribute("email"));

			String queryName	=	"recipe.mainMaterailSet";		
			String	query 	=	mappingQuery(req, queryName);
			String[] preparedIndex = {
					"main_material_pk",
					"recipe_pk"
			};
			//PreparedStatement  실행
			preparedExecuteUpdate(request, req, preparedIndex, query);		

	
			//디비연결 종
	        Transaction.end(request);
        
			req.put("SUCCESS_FAIL", "SUCCESS");
			req.put("MESSAGE", "수정 되었습니다..");
			
			return mapping.findForward( "success_fail" );         
													
			}catch(Exception e){
				e.printStackTrace();
				Transaction.rollback(request, response);
				req.put("system_error", e.getMessage());
				req.put("SUCCESS_FAIL", "FAIL");
				req.put("MESSAGE", "수정오류");
				return mapping.findForward( "success_fail" );			
			}   

	}
	
	public static void charSet(String str_kr) throws UnsupportedEncodingException{
        String charset[] = {"euc-kr", "ksc5601", "iso-8859-1", "8859_1", "ascii", "utf-8"};
            
        for(int i=0; i<charset.length ; i++){
            for(int j=0 ; j<charset.length ; j++){
                //if(i==j) continue;

      System.out.println(charset[i]+" : "+charset[j]+" :"+new String(str_kr.getBytes(charset[i]),charset[j]));
            }
        }
    }
	
	public ActionForward select( 	ActionMapping       mapping,
			ActionForm          form,
			HttpServletRequest  request,
			HttpServletResponse response ) throws Exception {
			Row	req			=	getRequestInfo(request);
		try{
			// 디비연결 시작
			Transaction.start(request);		

			req.put("searchType","title");
			//req.put("searchWord","네이버");
			try{
				System.out.println("searchWord:=================================1");
				charSet(req.getString("searchWord"));
				System.out.println("searchWord:=================================2");
			System.out.println("searchWord:"+(new String(req.getString("searchWord").getBytes("euc-kr"), "8859_1")));
			System.out.println("OOO_searchWord:"+req.getString("searchWord"));
			}catch(Exception e){
				e.printStackTrace();
			}
			//if(req.get("searchWord") != null){
			//req.put("searchWord", UtilMaster.toEng(req.getString("searchWord")));
			//}			
			
	        // 전체 게시물 갯수
			String totalQueryName	=	"newsMaster.selectTotal";		
			String	totalQuery 	=	mappingQuery(request, totalQueryName);
			
			simpleExecuteQueryGetOneRow(request, totalQuery, totalQueryName);
			
			Row	SUM_LIST	=	(Row)request.getAttribute(totalQueryName);
			req.put("TOTAL", SUM_LIST.getString("TOTAL"));					
			int start_row 	=	0;
			int page		=	0;
			//페이지 파라미터 점검
			//첫페이지는 파라미터가 없으므로 0이나 1로 셋팅한다.
			if(req.get("page") ==null || ((String)req.get("page")).trim().length() == 0 ){
				page	=	1;
			}else  {
				try{
					page	=	Integer.parseInt(((String)req.get("page")));
				}catch(Exception e){
					page	=	1;
				}
			}
			start_row	=	(page	-	1)	*	10;
			req.put("start_row", start_row+"");
			req.put("page", page+"");

			
			String listQueryName		=	"newsMaster.select";		
			String	listQuery 		=	mappingQuery(req, listQueryName);	
			simpleExecuteQuery(request, listQuery, listQueryName);												
	
			//디비연결 종
	        Transaction.end(request);
        
		}catch(Exception e){
			System.out.println("******"+e.getMessage());
			e.printStackTrace();
			Transaction.rollback(request, response);
			req.put("system_error", e.getMessage());
			return mapping.findForward( "system_error" );			
		}
		
		
		
		return mapping.findForward("select");
	}
	
	
	
	public ActionForward openCast( 	ActionMapping       mapping,
			ActionForm          form,
			HttpServletRequest  request,
			HttpServletResponse response ) throws Exception {
		Row	req			=	getRequestInfo(request);
		
		
		
		
		return mapping.findForward("openCast");
	}
	
	
	
}
